<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <h1>登录</h1>
      <el-card shadow="never" class="login-card">
        <!--登录表单-->
        <el-form v-if="showLogin === 'phone'" ref="form" :model="form" :rules="rules">
          <el-form-item prop="mobile">
            <el-input v-model="form.mobile" maxlength="11" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" placeholder="请输入密码" show-password />
          </el-form-item>
          <el-form-item prop="ischecked">
            <el-checkbox v-model="form.ischecked" label="用户平台使用协议" name="type" />
          </el-form-item>
          <el-form-item>
            <el-button
              style="width: 350px;"
              type="primary"
              class="login-btn"
              :loading="isloading"
              @click="onSubmit"
            >登录</el-button>
          </el-form-item>
        </el-form>
        <!-- 二维码登录 -->
        <div v-if="showLogin === 'multi'" v-loading="loading" class="multi">
          <template>
            <div>
              <img v-if="codeState" :src="qrImage" alt="QR Code" class="img">
              <div v-if="codeState === 2" class="img bgc">
                请在手机上确认登录
              </div>
              <div v-if="codeState === 3" class="img bgc">
                登录成功！
              </div>
              <div v-if="codeState === 4" class="img bgc" @click="refreshQRCode">
                二维码失效 请点击刷新
              </div>
              <div v-if="codeState === 5" class="img bgc" @click="refreshQRCode">
                取消登录
              </div>
            </div>
          </template>
        </div>
        <div class="multi-login">
          <el-button size="small" class="multi-button" @click="phoneLogin">手机号登录</el-button>
          <el-button size="small" class="multi-button" @click="multiLogin">扫码登录</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { getUserWorkId, getUserWorkIdStatus } from '@/api/user'
export default {
  name: 'Login',
  data() {
    // 表单验证规则:用户名
    const validateUser = (rule, value, callback) => {
      // 手机号正则
      const reg = /^1[3-9]\d{9}$/
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!reg.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        this.$refs.form.clearValidate('uername')
      }
      callback()
    }
    // 表单验证规则:密码
    const validatePass = (rule, value, callback) => {
      // 密码要求6到16位
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6 || value.length > 16) {
        callback(new Error('密码长度在 6 到 16 个字符'))
      } else {
        this.$refs.form.clearValidate('password')
      }
      callback()
    }
    // 表单验证规则:协议
    const validateChecked = (rule, value, callback) => {
      value ? callback() : callback(new Error('请先阅读并同意用户协议'))
    }
    return {
      showLogin: 'phone', // 登录方式
      qrImage: '', // 二维码图片地址
      qrcode_key: null, // 二维码key
      codeState: null, // 二维码状态
      loading: false, // 二维码加载中
      timer: null,
      form: {
        mobile: process.env.NODE_ENV === 'development' ? '13800000002' : '',
        password: process.env.NODE_ENV === 'development' ? 'hm#qd@23!' : '',
        ischecked: process.env.NODE_ENV === 'development'
      },
      isloading: false,
      rules: {
        mobile: [
          { validator: validateUser, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        ischecked: [
          { validator: validateChecked, trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    showLogin(newValue) {
      if (newValue === 'multi') {
        this.generateQRCode()
      } else {
        this.timer = null
      }
    }
  },
  mounted() {
    // 页面加载时自动生成二维码
    // this.generateQRCode()
  },
  methods: {
    phoneLogin() {
      this.showLogin = 'phone'
    },
    // 切换二维码登录
    multiLogin() {
      this.loading = true
      this.showLogin = 'multi'
    },
    // 刷新二维码
    async refreshQRCode() {
      this.loading = true
      this.generateQRCode()
    },
    // 生成二维码
    async generateQRCode() {
      // 这里可以替换为您想编码的内容
      this.qrcode_key = await getUserWorkId()
      this.qrImage = await QRCode.toDataURL(this.qrcode_key)

      this.timer = setInterval(async() => {
        const { codeState, token } = await getUserWorkIdStatus(this.qrcode_key)
        this.codeState = codeState
        this.loading = false
        // console.log(this.codeState)
        if (this.codeState === 3) {
          clearInterval(this.timer)
          this.$store.commit('user/SET_TOKEN', token)
          this.$router.push('/')
        }
      }, 1000)
    },
    async onSubmit() {
      this.isloading = true
      await this.$refs.form.validate()
      this.isloading = false
      // 请求完成后才跳转到首页
      await this.$store.dispatch('user/login', this.form)
      this.$router.push('/')
    }
  }
}
</script>

<style lang="scss">
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;

  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;

    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center / contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }

    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }

  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;

    .multi {
      width: 350px;
      height: 350px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .img {
        width: 250px;
        height: 250px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }

      .bgc {
        background-color: #bdb3b391;
        text-align: center;
        line-height: 250px;
        position: absolute;
        z-index: 99;
        color: #ffffff;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      }
    }

    .multi-login {
        margin: 10px 0;
        display: flex;
        width: 350px;

        .multi-button {
          flex: 1;
        }
      }

    .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

    .el-input {
      width: 350px;
      height: 44px;

      .el-input__inner {
        background: #f4f5fb;
      }
    }

    .el-checkbox {
      color: #606266;
    }
  }
}
</style>
